// pages/trainList/trainList.js
import {
  getTrainList,
} from '../../../api/train';
import {
  fetchPerson
} from '../../../api/user';
import {
  saveOrder,
  payOrder
} from '../../../api/order';
import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
import dayjs from 'dayjs';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    date: '',
    trainList: [],
    winHeight: 600,
    currentTab: '1',
    startstation: "",
    endstation: "",
    tickindex: 0,
    currentTrain: "",
    listLoading: 0,
    train: NaN,
    phoneNumber: "",
    pullDownRefreshing: false,
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
  },

  /**
   * 生命周期函数--监听页面加载，接收上一个界面传递过来的参数，并通过wx.setNavigationBarTitle来设置导航标题
   */
  onLoad: function (e) {
    this.data.startstation = e.startStation; //始发站
    this.data.endstation = e.endStation; //终点站
    var date = dayjs(e.date); //日期
    //wx.setNavigationBarTitle({title: this.data.startstation + '→' + this.data.endstation });
    this.setData({
      date: date.format('YYYY-MM-DD')
    });
    this.init(true);
  },
  onShow: function (e) {

    console.log("ddd")
    var that = this;
    console.log(that.data.mydata) //注需要提前声明mydata不然首次进来会报错
    this.fetchData()
  },

  onReTryLoad() {
    //this.getOrderList(this.data.curTab);
    this.fetchData()
  },
  /**
   * switchNav菜单来切换事件,动态设置页签导航选中效果
   */
  async init(reset = true) {
    const params = {
      start: this.data.startstation,
      end: this.data.endstation,
      date: this.data.date
    }
    try {
      getTrainList(params).then(result => {
        if (result.code === 2000) {
          const {
            data,
            total = 0
          } = result.data;
          if (total === 0 && reset) {
            this.total = total;
            this.setData({
              emptyInfo: {
                tip: '抱歉，未找到相关商品',
              },
              hasLoaded: true,
              loadMoreStatus: 0,
              loading: false,
              goodsList: [],
            });
            return;
          }
          const _goodsList = reset ? data : goodsList.concat(data);
          const _loadMoreStatus = _goodsList.length === this.total ? 2 : 0;
          this.pageNum = params.pageNum || 1;
          this.total = this.total;
          this.setData({
            trainList: _goodsList,
            loadMoreStatus: _loadMoreStatus
          });
        }
      })
    } catch (error) {
      this.setData({
        loading: false,
      });
    }
    this.fetchData()
  },
  onChange(e) {
    this.setData({
      train: e.detail.value
    })
  },
  onSubmit(e) {
    console.log(this.data.train)
    if (!this.data.train) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '没有选择线咱',
        theme: 'error',
      });
      return
    }
    if (!this.data.personInfo.phoneNumber) {
      const dialogConfig = {
        context: this,
        title: '下单失败',
        content: '没有填写电话号码,请完善个人资料',
        cancelBtn: '取消',
        confirmBtn: {
          content: '完善个人资料'
        },
      };
      Dialog.confirm(dialogConfig)
        .then(() => {
          wx.navigateTo({
            url: '/pages/usercenter/person-info/index'
          })
        })
        .catch(() => {
          console.log('点击取消');
        });
      return
    }

    saveOrder({
      "goods_id": this.data.train.id,
      "line_id": this.data.train.lineid,
      "times": this.data.train.time,
      "remark": "xcx",
      "mobile": 1,
      "nums": 1,
      "pay_method": 2
    }).then(result => {
      if (result.code !== 2000) {
        return
      }
      const {
        data,
        total = 0
      } = result.data;
      payOrder({
        "id": data.id,
        "platform": "xcx",
        "pay_type": "支付车票",
        "pay_method": 2
      }).then(result => {
        if (result.code !== 2000) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: result.msg,
            theme: 'error',
          });
          return
        }
        const {
          data,
          total = 0
        } = result.data;
        let res = data.wechataydata
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timestamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.sign,
          success: e => {
            wx.navigateTo({
              url: '/pages/order/pay-result/index?sts=1&totalPaid=' + 10 + 'orderNumbers=' + data.id + "&orderType=" + this.data.orderType,
            })
          },
          fail: err => {
            wx.navigateTo({
              url: '/pages/order/pay-result/index?sts=0&orderNumbers=' + data.id + "&orderType=" + this.data.orderType,
            })
          }
        })
      })
    })

    /*
    wx.navigateTo({
      url: `/pages/train/detail/index?id=`
    });*/
  },
  fetchData() {
    fetchPerson().then((res) => {
      const {
        data,
        total = 0
      } = res.data
      this.setData({
        personInfo: data
      });
    });
  },

  switchNav: function (e) {
    var id = e.currentTarget.id;
    this.setData({
      currentTab: id
    });
  },
  onPrevBtnTap: function () {
    var tomorrow = dayjs(new Date(Date.parse(this.data.date))).add(-1, 'day');
    this.setData({
      date: tomorrow.format('YYYY-MM-DD')
    });
    this.init(true);
  },
  onNextBtnTap: function () {
    var tomorrow = dayjs(new Date(Date.parse(this.data.date))).add(1, 'day');
    this.setData({
      date: tomorrow.format('YYYY-MM-DD')
    });
    this.init(true);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})